package com.itheima.bos.service.transit.impl;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.itheima.bos.dao.take_delivery.WayBillRepository;
import com.itheima.bos.dao.transit.TransitInfoRepository;
import com.itheima.bos.domain.take_delivery.WayBill;
import com.itheima.bos.domain.transit.TransitInfo;
import com.itheima.bos.index.WayBillIndexRepository;
import com.itheima.bos.service.transit.TransitInfoService;

@Transactional
@Service
public class TransitInfoServiceImpl implements TransitInfoService {
	
	@Autowired
	private WayBillRepository wayBillRepository;

	@Autowired
	private TransitInfoRepository transitInfoRepository;
	
	@Autowired 
	private WayBillIndexRepository wayBillIndexRepository;
	
	@Override
	public void createTransits(String wayBillIds) {
		
		if (StringUtils.isNoneBlank(wayBillIds)){
			String[] wayBillId = wayBillIds.split(",");
			for (String wayBillStr : wayBillId) {
				WayBill wayBill = wayBillRepository.findOne(Integer.parseInt(wayBillStr));
				
				//判断运单的状态是否为待发货
				if (wayBill.getSignStatus() == 1) {
					TransitInfo transitInfo = new TransitInfo();
					transitInfo.setWayBill(wayBill);
					transitInfo.setStatus("出入库中转");
					
					transitInfoRepository.save(transitInfo);
					
					//更改运单的状态为派送中
					wayBill.setSignStatus(2);
					//同步索引库
					wayBillIndexRepository.save(wayBill);
				}
			}
		}
		
	}

	@Override
	public Page<TransitInfo> findPageData(Pageable pageable) {
		
		return transitInfoRepository.findAll(pageable);
	}

}
